<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests\StoreAdminPost;
use App\Models\Admin;
use App\Models\MealCompany;

class AdminController extends Controller
{
    /**
     * 登陆页
     */
    public function login(Request $request) {
    	return view('manager.login');
    }

    /**
     * 执行登陆
     */
    public function loginAction(StoreAdminPost $request) {
    	$post = $request->only(['tel','password']);
    	$tel = trim($post['tel']);
    	$pass = md5(md5(trim($post['password'])));
    	$DataAdmin = Admin::where([['admin_tel','=',$tel],['status','=',1],['admin_passwd','=',$pass]])->select('admin_passwd','admin_id','admin_tel','region','admin_name','power')->first();
    	if(!$DataAdmin){
    		return response()->json(['errors'=>['password'=>['用户名或密码错误请重新输入！']],'messages'=>'用户名或密码错误请重新输入！'],422);
    	}
    	if($DataAdmin['admin_passwd']!==$pass){
    		return response()->json(['errors'=>['password'=>['用户名或密码错误请重新输入！']],'messages'=>'用户名或密码错误请重新输入！'],422);
    	}
        $DataAdmin['admin_ip'] = $request->getClientIp();
    	static::loginWrite($DataAdmin);
        if($DataAdmin['power'] == '*'){
            $url = '/';
        }else{
            $url = json_decode($DataAdmin['power'],true)[0];
        }
    	return response()->json(['success'=>'OK','messages'=>'登录成功！','url'=>$url]);
    }

    /**
     * 写入 session
     */
    private static function loginWrite($UserData) {
        $admin = Admin::find($UserData['admin_id']);
        $admin->admin_ip = '"'.$UserData['admin_ip'].'"';
        $admin->update_time = time();
        $admin->save();
        $data = ['admin_tel'=>$UserData['admin_tel'],'admin_id'=>$UserData['admin_id'],'region'=>$UserData['region'],'admin_name'=>$UserData['admin_name'],'power'=>$UserData['power']];
        if($UserData['region'] == 3){
            $data['company_id'] = MealCompany::where('admin_id',$UserData['admin_id'])->value('company_id');
        }
    	session($data);
    }

    /**
     * 退出登录
     */
    public function loginOut(Request $request) {
        $request->session()->flush();
        return redirect('/login');
    }
}
